package com.test.hand.client;

import com.test.hand.message.RpcRequestMessage;
import com.test.hand.protocol.MessageCodecSharable;
import com.test.hand.protocol.ProtocolFrameDecoder;
import com.test.hand.server.handler.RpcRequestMessageHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class RpcClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.INFO);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcRequestMessageHandler RPC_HANDLER = new RpcRequestMessageHandler();
        try {
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            // 防粘包处理器，（根据message_codec编写的防粘包处理器）
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(RPC_HANDLER);
                }
            });

            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            // 发送一个rpc消息
            channel.writeAndFlush(new RpcRequestMessage(
                    1,
                    "com.test.hand.server.service.HelloService",
                    "sayHello",
                    String.class,
                    new Class[]{String.class},
                    new Object[]{"张三"}
            )).addListener(promise -> {
                if (!promise.isSuccess()) {
                    Throwable throwable = promise.cause();
                    throwable.printStackTrace();
                }
            });
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }
}
